package com.asset.dispoal.file.agreementCaseData.service.commom;

import com.alibaba.excel.annotation.ExcelProperty;
import com.asset.dispoal.business.bsAgreement.domain.db.entity.BsDataDetail;
import com.asset.dispoal.business.bsAgreement.domain.db.mapper.BsDataDetailMapper;
import com.asset.dispoal.file.agreementCaseData.domain.dto.BsDataDetailExportTemplate;
import com.asset.dispoal.file.common.ExcelExport;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.springboot.protocol.Result;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

@Component
public class ExportExcelTemplateCommand implements BaseCommand<Map<String, Object>, Result> {

    @Autowired
    private BsDataDetailMapper dataDetailMapper;

    @SneakyThrows
    @Override
    public Result execute(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String assetInstBatchId = (String) map.get("assetInstBatchId");
        List<BsDataDetail> bsDataDetailList = this.dataDetailMapper.getDataDetailByAssetInstBatchId(assetInstBatchId);
        //获取Bar的val字段
        for (BsDataDetail bsDataDetail : bsDataDetailList) {
            Field field = BsDataDetailExportTemplate.class.getDeclaredField(bsDataDetail.getCode());
            //获取val字段上的ExcelProperty注解实例
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            //获取 excelProperty 这个代理实例所持有的 InvocationHandler
            InvocationHandler h = Proxy.getInvocationHandler(excelProperty);
            // 获取 AnnotationInvocationHandler 的 memberValues 字段
            Field hField = h.getClass().getDeclaredField("memberValues");
            // 因为这个字段事 private final 修饰，所以要打开权限
            hField.setAccessible(true);
            // 获取 memberValues
            Map memberValues = (Map) hField.get(h);
            // 修改 value 属性值
            String oldTable = ((String[]) memberValues.get("value"))[0];
//            bsDataDetail.getDataTypeName()
            memberValues.put("value", new String[]{oldTable,
                    bsDataDetail.getCode(),
                    bsDataDetail.getCustomName()});
        }

        ExcelExport.exportTemplate(response, "合同模板", BsDataDetailExportTemplate.class);
        return Result.ok();
    }
}
